import React, { useState, useEffect, useRef } from 'react'
import { Avatar, Modal, Image, DatePicker, message, Input } from 'antd';
import { ModalForm, ProFormDateRangePicker, ProFormSelect, ProTable, ProFormDigit } from '@ant-design/pro-components';
import TheButton from "@/components/TheButton/index.jsx";
import { apiGetUserList, apiGetCouponInfoList, apiGetByCouponCentre } from "@/api/couponManagement";
import { UserOutlined } from "@ant-design/icons";
import moment from 'moment';
import {useWindowSize} from "@/utils/useWindowSize.js";

const { confirm } = Modal;
const { RangePicker } = DatePicker;

export default () => {
  const {width, height} = useWindowSize();
  const [tbScrollH, setTbScrollH] = useState('40vh');
  const [modalVisit, setModalVisit] = useState(false);
  const [memberId, setMemberId] = useState();
  const actionRef = useRef();
  const columns = [
    {
      title: "ID",
      dataIndex: "memberId",
      key: "memberId",
      valueType: 'text',
      fieldProps: {
        maxLength: 8,
        onInput: (e) => {
          e.target.value = e.target.value.replace(/[^0-9]/g, '')
        }
      },
    },
    {
      title: "头像",
      dataIndex: "memberAvatar",
      key: "memberAvatar",
      hideInSearch: true,
      render: (text) => {
        if (text) {
          return <Avatar size="large" src={<Image src={text} />} />
        } else {
          return <Avatar size="large" icon={<UserOutlined />} />
        }
      }
    },
    {
      title: "昵称",
      dataIndex: "nickName",
      key: "nickName",
      hideInSearch: true
    },
    {
      title: "昵称",
      dataIndex: "wxNickName",
      key: "wxNickName",
      hideInTable: true
    },
    {
      title: "手机号",
      dataIndex: "memberMobile",
      key: "memberMobile",
    },
    {
      title: "身份",
      dataIndex: "memberType",
      key: "memberType",
      valueEnum: {
        'R': { text: '注册会员' },
        'P': { text: '正式会员' },
        'S': { text: '商户会员' },
      },
    },
    {
      title: "状态",
      dataIndex: "memberStatus",
      key: "memberStatus",
      valueEnum: {
        'Y': { text: '正常', status: 'Success' },
        'N': { text: '冻结', status: 'Error' },
      }
    },
    {
      title: "注册时间",
      dataIndex: "memberCreatedTime",
      key: "memberCreatedTime",
      renderFormItem: () => {
        return <ProFormDateRangePicker
          formItemProps={{
            className: 'form-rangePicker-w',
          }}
        />
      },
      search: {
        transform: (value) => {
          return {
            memberCreatedTimeStart: value ? moment(value[0]).format('YYYY-MM-DD') : undefined,
            memberCreatedTimeEnd: value ? moment(value[1]).format('YYYY-MM-DD') : undefined,
          };
        }
      }
    },
    {
      title: "操作",
      valueType: 'option',
      fixed: "right",
      render: (text, render) => {
        return (
          <div>
            <TheButton haspermi={['couponManagement:user:send']} type={'link'} onClick={() => openDialog(render.memberId)}>发放优惠券</TheButton>
          </div>
        );
      },
    },
  ]
  const openDialog = (id) => {
    setMemberId(id)
    setModalVisit(true)
  }
  useEffect(() => {
    if (height >= 1080){
      setTbScrollH('58vh')
    }else if(height < 1080 && height >= 960){
      setTbScrollH('47vh')
    }
  }, [])

  return <div>
    <ProTable
      actionRef={actionRef}
      scroll={{ x: "max-content", y: tbScrollH }}
      rowKey={(record) => record.memberId}
      bordered={true}
      options={false}
      columns={columns}
      pagination={{
        defaultPageSize: 10,
        position: ['bottomCenter'],
        showSizeChanger: false
      }}
      request={async (params, sort, filter) => {
        // 这里需要返回一个 Promise,在返回之前你可以进行数据转化
        // 如果需要转化参数可以在这里进行修改
        const res = await apiGetUserList({
          pageNo: params.current,
          pageSize: params.pageSize,
          ...params
        });
        return {
          data: res.data,
          // success 请返回 true，
          // 不然 table 会停止解析数据，即使有数据
          success: res.code === 0,
          // 不传会使用 data 的长度，如果是分页一定要传
          total: res.totalCount,
        };
      }}
      search={{
        optionRender: (searchConfig, formProps, dom) => {
          return dom.reverse()
        },
        collapsed: false,
        collapseRender: false
      }}
    />
    <ModalForm
      title="发放优惠券"
      layout={'horizontal'}
      labelCol={{ span: 5 }}
      wrapperCol={{ span: 19 }}
      width={500}
      open={modalVisit}
      modalProps={{
        destroyOnClose: true,
        onCancel: () => setModalVisit(false),
      }}
      submitTimeout={2000}
      onFinish={async (values) => {
        let res = await apiGetByCouponCentre({
          ...values,
          memberId: memberId,
          sourceId: 2
        })
        if (res.code === 0 && res.data) {
          if (res.data.success) {
            message.info('发放成功')
            // 刷新
            actionRef.current.reload();
            setModalVisit(false)
          } else {
            message.info(res.data.msg)
          }
        }
        return false;
      }}
    >
      <ProFormSelect
        request={async () => {
          let res = await apiGetCouponInfoList({ couponStatus: 'Y', deleted: 0 })
          if (res.code === 0) {
            return res.data
          }
        }}
        fieldProps={{
          fieldNames: {
            label: 'couponTitle',
            value: 'couponId'
          }
        }}
        rules={[
          {
            required: true,
            message: '请选择优惠券'
          },
        ]}
        width="md"
        name="couponId"
        label="优惠券"
        showSearch
        debounceTime={300}
      />
    </ModalForm>
  </div>
}
